<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户编号" prop="userId">
        <el-select v-model="queryParams.userId" filterable clearable placeholder="请选择用户" style="width: 150px;" >
          <!-- bugfix: Change to self-closing tags -->
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="个人账号" prop="myAccount">
        <el-input
          v-model="queryParams.myAccount"
          placeholder="请输入个人账号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="defaultStatus">
        <el-select
          v-model="queryParams.defaultStatus"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      
    
      <el-form-item label="存取日期" prop="saveDate">
        <el-date-picker
          v-model="queryParams.saveDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['member:fund:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增缴存
        </el-button>
        <!-- 新增提取按钮 -->
        <el-button
          type="success"
          plain
          @click="openWithdrawalForm"
        >
          <Icon icon="ep:minus" class="mr-5px" /> 新增提取
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['member:fund:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="用户编号" align="center" prop="userId" />
      <el-table-column label="个人账号" align="center" prop="myAccount" />
      <el-table-column label="状态" align="center" prop="defaultStatus" />
      <el-table-column label="账户余额" align="center" prop="accountBalance" />
      <el-table-column label="中心编号" align="center" prop="centerNumber" />
      <el-table-column label="中心名称" align="center" prop="centerName" />
      <el-table-column label="单位名称" align="center" prop="companyNumber" />
      <el-table-column label="单位账号" align="center" prop="companyAccount" />
      <el-table-column label="个人缴存比例" align="center" prop="myRatio" />
      <el-table-column label="单位缴存比例" align="center" prop="companyRatio" />
      <el-table-column label="个人缴存基数" align="center" prop="myBaseNumber" />
      <el-table-column label="个人月缴存额" align="center" prop="myAmount" />
      <el-table-column label="单位月缴存额" align="center" prop="companyAmount" />
      <el-table-column label="存取日期" align="center" prop="saveDate" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['member:fund:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['member:fund:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <FundForm ref="formRef" @success="getList" />

  <!-- 新增提取弹窗 -->
  <el-dialog
    v-model="withdrawalDialogVisible"
    title="新增提取"
    width="500px"
  >
    <el-form
      ref="withdrawalFormRef"
      :model="withdrawalFormData"
      :rules="withdrawalFormRules"
      label-width="80px"
    >
      <el-form-item label="请选择用户" prop="userId">
        <el-select v-model="withdrawalFormData.userId" filterable placeholder="请选择用户">
          <!-- bugfix: Change to self-closing tags -->
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提取金额" prop="allAmount">
        <el-input
          v-model="withdrawalFormData.allAmount"
          placeholder="请输入提取金额"
        />
      </el-form-item>
      <el-form-item label="存取日期" prop="saveDate">
        <el-date-picker
          v-model="withdrawalFormData.saveDate"
          type="date"
          placeholder="选择日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="new Date('1 00:00:00')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeWithdrawalForm">取消</el-button>
      <el-button type="primary" @click="saveWithdrawalForm">保存</el-button>
    </template>
  </el-dialog>
  
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { FundApi, FundVO } from '@/api/member/fund'
import FundForm from './FundForm.vue'
import * as UserApi from '@/api/member/user'

/** 会员公积金 列表 */
defineOptions({ name: 'Fund' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<FundVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  myAccount: undefined,
  defaultStatus: undefined,
  accountBalance: undefined,
  centerNumber: undefined,
  centerName: undefined,
  companyNumber: undefined,
  companyAccount: undefined,
  myRatio: undefined,
  companyRatio: undefined,
  myBaseNumber: undefined,
  myAmount: undefined,
  companyAmount: undefined,
  saveDate: [],
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


const statusOptions = [
  {
    value: '0',
    label: '全部'
  },
  {
    value: '1',
    label: '缴存'
  },
  {
    value: '2',
    label: '提取'
  }
];

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FundApi.getFundPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await FundApi.deleteFund(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await FundApi.exportFund(queryParams)
    download.excel(data, '会员公积金.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  userHandleQuery()
})

const userOptions = ref([])

const userQueryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  nickname: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: null,
  groupId: null
})

/** 搜索按钮操作 */
const userHandleQuery = () => {
  userQueryParams.pageNo = 1
  getUserList()
}

/** 查询列表 */
const getUserList = async () => {
  try {
    const data = await UserApi.getUserPage(userQueryParams)
    userOptions.value = data.list.map((item) => ({
      label: item.nickname,
      value: item.id
    }))
  } finally {
    console.log('获取用户列表失败')
  }
}

// 新增提取弹窗相关变量
const withdrawalDialogVisible = ref(false)
const withdrawalFormRef = ref()
const withdrawalFormData = reactive({
  defaultStatus: 2,
  userId: undefined,
  allAmount: '',
  saveDate: []
})
const withdrawalFormRules = reactive({
  allAmount: [
    { required: true, message: '提取金额不能为空', trigger: 'blur' }
  ],
  saveDate: [
    { required: true, message: '存取日期不能为空', trigger: 'blur' }
  ]
})

// 打开新增提取弹窗
const openWithdrawalForm = () => {
  console.log('openWithdrawalForm called'); // 添加日志，检查方法是否被调用
  withdrawalDialogVisible.value = true;
};

// 关闭新增提取弹窗
const closeWithdrawalForm = () => {
  withdrawalDialogVisible.value = false
}

// 保存新增提取表单
const saveWithdrawalForm = async () => {
  try {
    await new Promise((resolve, reject) => {
      withdrawalFormRef.value.validate((valid) => {
        if (valid) {
          resolve(true)
        } else {
          reject(new Error('表单验证失败'))
        }
      })
    })
    // 这里可以添加保存数据的逻辑，例如调用 API
    console.log('保存提取数据:', withdrawalFormData)
    message.success('保存成功')
    closeWithdrawalForm()
    getList() // 刷新列表
  } catch (error) {
    message.error('保存失败')
  }
}
</script>